import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/network/UrlPath.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:pinput/pinput.dart';

import '../../r.dart';
import 'login_logic.dart';

/**
 * @Description: 登录页面
 * @Author: 下雨了
 * @CreateDate: 2022年6月20日 14:44:21
 * @Version: 1.0
 */
///
class LoginPage extends StatefulWidget {
  final String title;

  const LoginPage({Key? key, required this.title}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final logic = Get.put(LoginLogic());
  final state = Get.find<LoginLogic>().state;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginLogic>(builder: (logic) {
      return Scaffold(
        resizeToAvoidBottomInset: false,/*可以通过设置 这个属性 防止键盘 覆盖内容 或者 键盘 撑起内容*/
        backgroundColor: MyColors.FFF5F5F5,
        body: GestureDetector(
          child: Stack(
            children: [
              Align(
                child: Image.asset(R.assetsImgBg3),
                alignment: Alignment.bottomCenter,
              ),
              SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    // 头部图标
                    SafeArea(
                      child: GestureDetector(
                        child: Container(
                          margin: EdgeInsets.only(top: 80.r),
                          width: 72.r, height: 72.r,
                          alignment: Alignment.center,
                          child: ClipOval(
                            child: Image.asset(R.assetsImgLogo, fit: BoxFit.cover),
                          ),
                        ),
                        onTap: () {
                          tapCount();
                        },
                      ),
                    ),
                    // 账号输入框
                    Container(
                      margin: EdgeInsets.fromLTRB(20.r, 50.r, 20.r, 0),
                      child: Row(
                        children: [
                          Container(
                              margin: EdgeInsets.only(right: 12.r),
                              child: Image.asset(R.assetsImgIcon44, width: 18.r,)),
                          Expanded(
                            child: TextField(
                              controller: logic.userName,
                              autofocus: false,
                              style: TextStyle(color: MyColors.FF333333, fontSize: 18.sp),
                              decoration: InputDecoration(
                                  //不需要输入框下划线
                                  border: InputBorder.none,
                                  hintText: '请输入手机号码或者账号',
                                  hintStyle: TextStyle(color: MyColors.FF999999, fontSize: 14.sp)),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(20.r, 0, 20.r, 0),
                      child: Divider(height: 1.0, color: MyColors.FFE6E6E6),
                    ),
                    // 密码输入框
                    Container(
                      margin: EdgeInsets.fromLTRB(20.r, 20.r, 20.r, 0),
                      child: Row(
                        children: [
                          Container(
                            margin: EdgeInsets.only(right: 12.r),
                            child: Image.asset(R.assetsImgIcon42, width: 18.r,),
                          ),
                          Expanded(
                            child: TextField(
                              controller: logic.password,
                              autofocus: false,
                              obscureText: true,
                              style: TextStyle(color: MyColors.FF333333, fontSize: 18.sp),
                              decoration: InputDecoration(
                                  //不需要输入框下划线
                                  border: InputBorder.none,
                                  hintText: '请输入密码',
                                  hintStyle: TextStyle(color: MyColors.FF999999, fontSize: 14.sp)),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(20.r, 0, 20.r, 0),
                      child: Divider(height: 1.0, color: MyColors.FFE6E6E6),
                    ),
                    Container(
                      margin: EdgeInsets.only(right: 20.r),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: TextButton(
                          child: Text("忘记密码", style: TextStyle(color: MyColors.FF999999, fontSize: 13.sp),),
                          style: ButtonStyle(
                            padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                          ),
                          onPressed: () {
                            logic.goToPasswordResetPage();
                          },
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(20.r, 70.r, 20.r, 0),
                      height: 50.r,
                      width: MediaQuery.of(context).size.width,
                      child: ElevatedButton(
                        child: Text("登录", style: TextStyle(color: MyColors.FFFFFFFF, fontSize: 14.sp),),
                        style: ButtonStyle(
                          padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                          backgroundColor: MaterialStateProperty.all<Color>(MyColors.FFE5261E),
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(Radius.circular(5)),
                            ),
                          ),
                        ),
                        onPressed: () {
                          logic.login();
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          onTap: () {
            // 空白处取消TextField焦点
            FocusScopeNode currentFocus = FocusScope.of(context);
            if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
              FocusManager.instance.primaryFocus!.unfocus();
            }
          },
        ),
      );
    });
  }

  // 底部弹窗切换
  void showRerouting() {
    print("123123");
    List<BrnCommonActionSheetItem> actions = [];
    actions.add(BrnCommonActionSheetItem(
      '选项一（开发）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '选项一（测试）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '选项一（生产）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (_) {
        return BrnCommonActionSheet(
          actions: actions,
          clickCallBack: (int index, BrnCommonActionSheetItem actionEle) {
            print(index);
            String title = actionEle.title;
            switch (index) {
              case 0:
                UrlPath.baseUrl = "http://192.168.3.196:8601/";
                break;
              case 1:
                UrlPath.baseUrl = "https://xxx.szzfyjzx.icu:5236/";
                break;
              case 2:
                UrlPath.baseUrl = "https://www.xnah.gov.cn";
                break;
              default:
            }
          },
        );
      },
    );
  }

  // 输入框
  void showInput() {
    final defaultPinTheme = PinTheme(
      width: 42.r,
      height: 42.r,
      textStyle: TextStyle(fontSize: 20.sp, color: MyColors.FF333333),
      decoration: BoxDecoration(
        color: MyColors.FFF1F1F1,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.transparent),
      ),
    );

    final focusedPinTheme = defaultPinTheme.copyWith(
      width: 45.r,
      height: 45.r,
      decoration: defaultPinTheme.decoration!.copyWith(
        border: Border.all(color: MyColors.FF2763B9),
      ),
    );

    showDialog(context: context, builder: (BuildContext context) {
      return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(13.33.r),
          ),
          insetPadding: EdgeInsets.symmetric(horizontal: 24.0.r, vertical: 24.0.r),
          child: IntrinsicHeight(
            child: Container(
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 17.5.r),
                    child: Text("管理员模式", style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.w500),),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 11.5.r, left: 16.r, right: 16.r,),
                    height: 45.r,
                    child: Pinput(
                      length: 6,
                      defaultPinTheme: defaultPinTheme,
                      focusedPinTheme: focusedPinTheme,
                      autofocus: true,
                      onCompleted: (value) {
                        if (value == "111111") {
                          Navigator.of(context).pop('ok');
                          showRerouting();
                        } else {
                          toast.show("密码错误，耗子尾汁！！！");
                        }
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 11.5.r),
                    height: 45.r,
                    child: TextButton(
                      child: Text("确认", style: TextStyle(color: MyColors.FF2763B9, fontSize: 14.sp, fontWeight: FontWeight.w500),),
                      style: ButtonStyle(padding: MaterialStateProperty.all(EdgeInsets.all(0)),),
                      onPressed: () {
                        Navigator.of(context).pop('ok');
                      },
                    ),
                  ),
                ],
              ),
            ),
          )
      );
    });
  }


  Timer? timer;
  int count = 0;

  /// 连续点击10次 切换baseUrl
  void tapCount() {
    count++;
    timer?.cancel();
    timer = Timer(Duration(milliseconds: 500), () {
      if (count >= 10) {
        showInput();
      }
      count = 0;
    });
  }

  @override
  void dispose() {
    Get.delete<LoginLogic>();
    timer?.cancel();
    super.dispose();
  }
}
